import Global_1 from './config.js'
import SocketUser_1 from './SocketUser.js'
import Queue_1 from './Queue.js'

var WebSocketHelper = (function() {

	function WebSocketHelper(model, ws, v) {

		var that = this;

		that.vue = v;

		that.projectInfo = model;

		that.ws = ws;

		// 是否可以重连
		that.isReload = true;

		// 是否连接
		that.isLink = false;

		// 是否有网络连接
		that.isConnected = false;

		// 心跳
		that.heartbeat = null;

		// 重连
		that.reloadLink = null;
		
		// 查找历史 token
		that.clientToken = uni.getStorageSync(that.projectInfo.uuid);

		this.ws.onnetwork = function(status) {};

		uni.getNetworkType({
			success: function(res) {
				setTimeout(function() {
					switch (res.networkType) {
						case 'none':
							that.onnetwork(false);
							that.isConnected = false;
							break;
						default:
							that.onnetwork(true);
							that.isConnected = true;
							uni.connectSocket({
								url: Global_1.Global.WssService
							});
							break;
					}
				}, 1000);
			}
		});

		uni.onNetworkStatusChange(function(res) {
			that.onnetwork(res.isConnected);
			if (!that.isConnected) {
				if (res.isConnected && that.isReload) {
					console.info('正在尝试重连...');
					that.reload();
				}
			}
			that.isConnected = res.isConnected;
		});
	}

	/** 验证身份 获取 ClientToken */
	WebSocketHelper.prototype.Authentication = function(model) {
		var that = this;
		that.vue.islink = true;
		if (that.clientToken) {
			that.ws.send({
				data: "ixpe_userlogin:" + that.clientToken
			});
		} else {
			var socketUser = new SocketUser_1.SocketUser();
			socketUser
				.LoginWsByClient(model, function(e) {

					console.info('userKey:' + e.date.id);
					console.info('clientToken:' + e.info);
					
					uni.setStorageSync(that.projectInfo.uuid,e.info);

					that.vue.userId = e.date.id;

					Global_1.UserInfo(e.date);

					that.clientToken = e.info;
					that.ws.send({
						data: "ixpe_userlogin:" + that.clientToken
					});
				});
		}
	};

	/** 退出 ServiceToken */
	WebSocketHelper.prototype.OutLogin = function(token) {
		var that = this;
		var socketUser = new SocketUser_1.SocketUser();
		socketUser
			.OutLoginWs(token, function(e) {
				console.info(e.data);
			});
	};

	WebSocketHelper.prototype.send = function(msg, callback, error) {
		if (callback === void 0) {
			callback = null;
		}
		if (error === void 0) {
			error = null;
		}
		var model = msg;
		model.ClientToken = this.clientToken;
		model.Template = "WebSocket";
		var queue = new Queue_1.Queue();
		queue.Push(msg, function(e) {
			if (e.code == 200) {
				callback && callback(e);
			} else {
				error && error(e.info);
			}
		}, error);
	};

	/** 重新连接 */
	function reloadLinkAction(that) {

		that.reloadLink = setInterval(function() {
			if (Global_1.AppOnStatus()) {
				if (!that.isLink) {
					if (that.isConnected) {
						if (that.isReload) {
							console.info('正在尝试重连....');
							that.reload();
						}
					} else {
						console.info('暂无网络...');
					}
				} else {
					clearInterval(that.reloadLink)
				}
			}

		}, 3000);
	}

	WebSocketHelper.prototype.onopen = function(event) {
		var that = this;
		this.ws.onopen(function() {

			that.isLink = true;
			event && event();
			that.Authentication(that.projectInfo);

			clearInterval(that.reloadLink);

			that.heartbeat = setInterval(function() {

				if (Global_1.AppOnStatus()) {
					uni.sendSocketMessage({
						data: '1',
						success: function() {
							var reg = new RegExp(":", "g")
							var heartbeattime = that.vue.heartbeattime.replace(reg, "") - 0;

							var datatime = new Date();
							var 
								hours = datatime.getHours()+'',
								minutes = datatime.getMinutes()+'',
								seconds = datatime.getSeconds()+'';

							hours = hours.length > 1 ? hours + '' : '0' + hours;
							minutes = minutes.length > 1 ? minutes + '' : '0' + minutes;
							seconds = seconds.length > 1 ? seconds + '' : '0' + seconds;

							var thisTime = (hours + minutes + seconds) - 0;
							var lastHeartBeatTime = that.vue.heartbeatintervaltime < 30 & that.vue.heartbeatintervaltime > 15;
							that.vue.heartbeatintervaltime = thisTime - heartbeattime;

							// 心跳超时 [第二次超时才会断开]
							if (lastHeartBeatTime & that.vue.heartbeatintervaltime < 30 & that.vue.heartbeatintervaltime > 15) {
								console.error('heart beat interval time timeout! try reload...')
								clearInterval(that.heartbeat);
								that.isLink = false;
								uni.closeSocket();
								reloadLinkAction(that);
							}
						},
						fail: function() {
							clearInterval(that.heartbeat);
							that.isLink = false;
							uni.closeSocket();
							reloadLinkAction(that);
						}
					})
				} else {
					uni.closeSocket();
				}



			}, 5000);

		});
	};

	WebSocketHelper.prototype.onmessage = function(event) {
		var that = this;
		this.ws.onmessage(function(e){
			
			var result = JSON.parse(e.data);
			
			switch (result.type) {
				case 'userlogin':
					if ((result.date+'') != '200') {
						uni.setStorageSync(that.projectInfo.uuid,'');
						that.clientToken = null;
						that.Authentication(that.projectInfo);
					}else{
						console.log('Wss用户身份验证成功')
					}
					break;
				default:
					event && event(result);
					break;
			}
			
			
		});
	};

	WebSocketHelper.prototype.onnetwork = function(event) {
		this.onnetwork = event;
	};

	WebSocketHelper.prototype.onclose = function(event) {
		var that = this;

		this.ws.onclose(function() {

			clearInterval(that.heartbeat);

			that.vue.islink = false;

			that.isLink = false;
			event && event();

			setTimeout(function() {
				if (that.isConnected) {
					if (that.isReload) {
						console.info('正在尝试重连...');
						that.reload();
					}
				} else {
					console.info('暂无网络...');
				}
			}, 500);

		});
	};

	WebSocketHelper.prototype.reload = function() {
		if (Global_1.AppOnStatus()) {
			uni.connectSocket({
				url: Global_1.Global.WssService
			});
		} else {
			console.log('当前后台运行取消重试')
		}

	}

	// 页面显示尝试重新加载
	WebSocketHelper.prototype.showReload = function() {
		reloadLinkAction(this);
	}

	return WebSocketHelper;
}());


export default {
	WebSocketHelper: WebSocketHelper
};
